#include "Semaphore.h"
#include "Thread.h"
#include "RWLock.h"
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace qy;
Semaphore *g_sem;
std::string g_message = "hello";
RWLock *g_lock;

class reader : public Thread
{
protected:
	int run()
	{
		while(!m_stop)
		{
				printf("%lu wants to read\n", threadId());
				g_lock->rdlock();
				sleep(5);
				printf("%lu reads %s\n", threadId(), g_message.c_str());
				g_lock->unlock();
				sleep(1);
		}
	}
};

class writer: public Thread
{
protected:
	int run()
	{
		const char *str[] = {"hello", "world", "hi", "cpp", "java",
		"tom", "beckham"};
		int i = 0;
		while(!m_stop)
		{
		printf("%lu wants to write\n", threadId());
		g_lock->wrlock();
		g_message = std::string(str[(i++)%5]);
		sleep(1);
		printf("%lu writes %s\n", threadId(), g_message.c_str());
		g_lock->unlock();
		sleep(1);
		}
	}

};


class Task : public Thread
{
protected:
	int run()
	{
		printf("I am %lu, waiting\n", threadId());
		g_sem->wait();
		int v;
		g_sem->value(v);
		printf("I am %lu, remain %d\n", threadId(), v);
		sleep(1);
		g_sem->post();
		printf("I am %lu, 88\n", threadId());
		return 0;
	}
};


int main(int argc, char *argv[])
{	
/*	g_sem = Semaphore::create(3);
	for(int i = 0; i < 10; i++)
	{
		Task *t = new Task();
		t->start();
	}*/
	g_lock = RWLock::create();

	reader *r1 = new reader();
	reader *r2 = new reader();
	reader *r3 = new reader();
	writer *w = new writer();
	r1->start();
	r2->start();
	r3->start();
	w->start();

	RWLock::destroy(g_lock);

	for(;;);

	return 0;
}
